<!--
禁止修改!此文件是产品代码的一部分，后续可能变更或者不再开放。
若有问题，请参考前端相关二开文档。
-->
<template>
  <div>
    <h3-checkbox-list
      v-if="isMultiple"
      showMode="0"
      showHeaderSearch
      :options="options"
      class="report-dropdown"
      :value="currentValue"
      :cancelText="$t('cloudpivot.form.renderer.cancel')"
      :okText="$t('cloudpivot.form.renderer.ok')"
      :clearText="$t('cloudpivot.form.renderer.clear')"
      :notFoundText="$t('cloudpivot.form.renderer.noOptions')"
      :checkAllText="$t('cloudpivot.form.renderer.checkAll')"
      @onChange="onChange"
    />
    <h3-radio-list
      v-else
      showHeaderSearch
      showMode="0"
      :options="options"
      class="report-dropdown"
      :value="currentValue"
      :cancelText="$t('cloudpivot.form.renderer.cancel')"
      :okText="$t('cloudpivot.form.renderer.ok')"
      :clearText="$t('cloudpivot.form.renderer.clear')"
      :notFoundText="$t('cloudpivot.form.renderer.noOptions')"
      @onChange="onChange"
    />
  </div>
</template>

<script lang="ts">
import axios from 'axios';
import { DataItemType } from 'cloudpivot-form/form/schema';
import { listApi } from 'cloudpivot/api';
import common from 'cloudpivot/common';
import { H3CheckboxList, H3RadioList } from 'h3-mobile-vue';
import { Component, Model, Prop, Vue } from 'vue-property-decorator';

@Component({
  name: 'report-dropdown',
  components: {
    H3CheckboxList,
    H3RadioList,
  },
})
export default class ReportDropdown extends Vue {
  @Prop({
    default() {
      return [];
    },
  })
  value!: any[];

  @Model('change')
  @Prop({
    default: () => ({}),
  })
  field!: any;

  @Prop({
    default: '',
  })
  formula!: string;

  currentPage: number = 0; //当前页码

  get mode() {
    if (this.isMultiple) {
      return 'multiple';
    }
    return 'default';
  }

  get isMultiple() {
    return (
      ['In', 'NotIn'].includes(this.formula) ||
      this.field.dataType === DataItemType.Checkbox ||
      this.field.dataType === DataItemType.DropdownMulti
    );
  }

  get currentValue() {
    return this.isMultiple ? this.value : this.value.join(';');
  }

  set currentValue(value) {
    this.$emit('input', value);
  }

  created() {
    this.init();
  }

  async init() {
    const vm: any = this;
    const params = {
      schemaCode: this.field.parentSchemaCode || this.field.schemaCode,
    };
    axios.get('/api/app/bizproperty/list', { params }).then(async (res) => {
      const data = res.data;
      if (Array.isArray(data)) {
        let item = data.filter((i: any) => {
          return i.code === (vm.field.mainField || vm.field.field);
        });
        if (vm.field.mainField) {
          const subData = item[0].subSchema && item[0].subSchema.properties;
          item = subData.filter((i: any) => {
            return i.code === vm.field.field;
          });
        }
        const optionsController = new common.utils.OptionsStrategyCollector(
          item[0].options,
        );
        const options = await optionsController.parseOptions(0, '');
        vm.options = options.map((o: any) => o.label);
      } else {
        return;
      }
    });
  }

  options: any[] = [];

  onChange(val: any) {
    const value = this.isMultiple ? val : val.value;
    this.$emit('input', value);
  }

  filterOption(input: any, option: any) {
    return (
      option.componentOptions.children[0].text
        .toLowerCase()
        .indexOf(input.toLowerCase()) >= 0
    );
  }

  /**
   * 获取业务模型数据
   */
  getOptions(
    schemaCode: string,
    queryCode: string,
    params: any[],
    sheetDataItem: string,
    orderByFields: string[],
    orderType: number,
    condition: any,
  ) {
    const filters = params.map((x) => {
      let val: any = x.value;
      if (x.propertyCode === 'sequenceStatus') {
        switch (val) {
          case '草稿':
            x.value = 'DRAFT';
            break;
          case '进行中':
            x.value = 'PROCESSING';
            break;
          case '已完成':
            x.value = 'COMPLETED';
            break;
          case '已作废':
            x.value = 'CANCELED';
            break;
          default:
            break;
        }
      }
      switch (x.type) {
        case DataItemType.RelevanceForm:
          val = x.value.id || '';
          break;
        case DataItemType.StaffSingle:
        case DataItemType.StaffMulti:
        case DataItemType.StaffDeptMix:
        case DataItemType.DeptMulti:
        case DataItemType.DeptSingle:
          val = x.value.map((v: any) => ({
            id: v.id,
            type: v.unitType || v.type,
          }));
          val = JSON.stringify(val);
          break;
        case DataItemType.Number:
          if (Array.isArray(x.value)) {
            val = x.value.map((v) => v.toString()).join(';');
          } else {
            val = x.value;
          }
          break;
        default:
          if (Array.isArray(x.value)) {
            val = x.value.map((v) => v.toString()).join(';');
          } else {
            val = x.value;
          }
          break;
      }
      return {
        propertyCode: x.propertyCode,
        propertyValue: val,
        op: 'Eq',
      };
    });
    const options = {
      customDisplayColumns: [sheetDataItem],
    };
    const obj: any = {
      queryCode,
      schemaCode,
      options,
      orderByFields,
      orderType,
      page: 0,
      size: 10000,
      filters,
      condition,
    };
    return listApi.listSkipQueryList(obj).then((res) => {
      if (res.errcode === 0) {
        const data: string[] = [];
        res.data.content.forEach((x: any) => {
          const s = x.data[sheetDataItem];
          let t = '';
          if (s && data.indexOf(s) === -1) {
            if (sheetDataItem === 'sequenceStatus') {
              switch (s) {
                case 'DRAFT':
                  t = '草稿';
                  break;
                case 'PROCESSING':
                  t = '进行中';
                  break;
                case 'COMPLETED':
                  t = '已完成';
                  break;
                case 'CANCELED':
                  t = '已作废';
                  break;
                default:
                  break;
              }
              data.push(t);
            } else {
              data.push(s);
            }
          }
        });
        return data;
      }
      return [];
    });
  }

  getShowOpt(opt: any) {
    if (typeof opt === 'string') {
      return opt;
    } else {
      return opt[0].name;
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.report-dropdown {
  padding: 5px;
  .h3-field-layout-h-label {
    display: none;
  }
  .h3-field-placeholder {
    margin: 0;
  }
}
</style>
